package cn.microservices.cloud.common.mybtis.handlers;

import cn.microservices.cloud.common.mybtis.core.enums.Flag;
import cn.microservices.cloud.common.web.utils.CommonRequestUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * Mybatis-Plus 数据自动填充
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String identityId = CommonRequestUtils.getId();
        log.info("Insert 数据库自动填充 identityId={}",identityId);
        this.strictInsertFill(metaObject, "insertTime", () -> LocalDateTime.now(), LocalDateTime.class);
        this.strictInsertFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);
        this.strictInsertFill(metaObject, "availableFlag", () -> Flag.YES.getCode(), String.class);
        if (StringUtils.isNotEmpty(identityId)){
            this.strictInsertFill(metaObject, "insertUser", () -> identityId, String.class);
            this.strictInsertFill(metaObject, "updateUser", () -> identityId, String.class);
        }
        this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String identityId = CommonRequestUtils.getId();
        log.info("Update 数据库自动填充 identityId={}",identityId);
        if (StringUtils.isNotEmpty(CommonRequestUtils.getId())){
            this.strictInsertFill(metaObject, "updateUser", () -> identityId, String.class);
        }
        this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class);
    }
}